package tech.aistar.day13;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 本类用来演示: 反射操作构造
 *
 * @author: success
 * @date: 2022/8/4 11:06 上午
 */
public class ConstructorDemo {
    public static void main(String[] args) {
        Point p = new Point();
        Class<?> c = p.getClass();

        Constructor<?>[] constructors = c.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }

        System.out.println("==反射调用构造==");

        //1. 空参构造调用的第一种方式 - Constructor提供的newInstance方法
        //根据指定的参数列表来获取指定的构造
        try {
            Constructor c1 = c.getDeclaredConstructor();
            //反射调用构造来构建对象
            Point p2 = (Point) c1.newInstance();

            //Class提供的newInstance方法
            Point p3 = (Point) c.newInstance();

            //2. 调用带参构造
            Constructor c2 = c.getDeclaredConstructor(String.class,int.class);
            Point p4 = (Point) c2.newInstance("admin",18);
            System.out.println(p4);

            //2-1. 调用私有的构造
            Constructor c3 = c.getDeclaredConstructor(String.class);
            //私有的构造
            c3.setAccessible(true);
            Point p5 = (Point) c3.newInstance("python");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
